import CryptoJS from "crypto-js";
import { preview, source } from "../api/api";
function generateSign(secret: any, params: any) {
  var fullParamStr = uniqSortParams(params);
  return hmacSHA256(fullParamStr, secret);
}

function uniqSortParams(params: any) {
  delete params.sign;

  var var5 = [];
  var var6 = 0;
  for (var key in params) {
    var5[var6] = key;
    var6++;
  }
  var5.sort(function (a:any, b:any) {
    return a.localeCompare(b, "zh-CN");
  });

  var result = "";
  for (var var7 = 0; var7 < var5.length; var7++) {
    var key = var5[var7];
    var var8 = params[key];
    var8.sort(function (a, b) {
      return a.localeCompare(b, "zh-CN");
    });

    if (var8 != null && var8.length > 0) {
      for (var var9 = 0; var9 < var8.length; var9++) {
        result += key + "=" + var8[var9];
      }
    } else {
      result += key + "=";
    }
  }
  return result;
}

function hmacSHA256(data: any, key: string) {
  data != null ? data : "";
  var var2 = CryptoJS.HmacSHA256(data, key);
  var var3 = var2.toString(CryptoJS.enc.Hex);
  return var3.toUpperCase();
}

const yozo = async (fileurl: string, line?: boolean) => {
  console.log(fileurl)
  // 取消请求;
  source ? source() : "";

  if (
    fileurl.indexOf(".pdf") > -1 ||
    fileurl.indexOf(".jpg") > -1 ||
    fileurl.indexOf(".png") > -1 ||
    fileurl.indexOf(".jpeg") > -1 ||
    fileurl.indexOf(".PDF") > -1 ||
    fileurl.indexOf(".JPG") > -1 ||
    fileurl.indexOf(".PNG") > -1 ||
    fileurl.indexOf(".JPEG") > -1
  ) {
    return fileurl+'#toolbar=0';
  } else {
    if (line) {
      return `https://view.officeapps.live.com/op/view.aspx?src=${fileurl}`;
    } else {
      let sign = generateSign("9aa756b3b52185f448ee33cbde48", {
        appId: ["yozoPOpoDhbp4200"],
        fileUrl: [fileurl],
      });
      let res: any = await preview({
        fileUrl: fileurl,
        sign: sign,
        appId: "yozoPOpoDhbp4200",
      });
      console.log({
        fileUrl: fileurl,
        sign: sign,
        appId: "yozoPOpoDhbp4200",
      })
     
      let sign2 = generateSign("9aa756b3b52185f448ee33cbde48", {
        appId: ["yozoPOpoDhbp4200"],
        fileVersionId: [res.data.fileVersionId],
      });
      console.log(res);
      return `https://eic.yozocloud.cn/api/view/file?fileVersionId=${res.data.fileVersionId}&appId=yozoPOpoDhbp4200&sign=${sign2}`;
    }
  }
};

export { yozo };
